package com.yiqiang;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.net.URISyntaxException;

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

import static android.app.Notification.VISIBILITY_PUBLIC;


/**
 * A login screen that offers login via username.
 */
public class LoginActivity extends Activity {

    private EditText mUsernameView;

    private String mUsername;

    private Socket mSocket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        mUsernameView = (EditText) findViewById(R.id.username_input);
        mUsernameView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        findViewById(R.id.connect_button).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mSocket  = IO.socket("http://iotac.tianren.com"+ ":" + 3909 + "/");
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
                mSocket.on("connect", message);
                mSocket.on("dateEvent", onlineCount);
                //mSocket.on(Socket.EVENT_CONNECT,OnConnect);
                //mSocket.on(Socket.EVENT_CONNECT_ERROR,OnConnectError);
                mSocket.connect();
            }
        });


        Button signInButton = (Button) findViewById(R.id.sign_in_button);
        signInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });


    }
    private Emitter.Listener OnConnect = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            Log.i("MM","OnConnect="+args[0].toString());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(LoginActivity.this,args[0].toString(),Toast.LENGTH_SHORT).show();
                }
            });
        }
    };
    private Emitter.Listener OnConnectError = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            Log.i("MM","OnConnectError="+args[0].toString());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(LoginActivity.this,args[0].toString(),Toast.LENGTH_SHORT).show();
                }
            });
        }
    };
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSocket.disconnect();
        mSocket.off("new_msg", message);
        mSocket.off("update_online_count", onlineCount);

    }

    private void attemptLogin() {
        // Reset errors.
        mUsernameView.setError(null);

        // Store values at the time of the login attempt.
        String username = mUsernameView.getText().toString().trim();

        // Check for a valid username.
        if (TextUtils.isEmpty(username)) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            mUsernameView.setError(getString(R.string.error_field_required));
            mUsernameView.requestFocus();
            return;
        }

        mUsername = username;

        // perform the user login attempt.
        mSocket.emit("login", username);
    }




    private Emitter.Listener message = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            Log.i("MM","22");
//            Toast.makeText(LoginActivity.this,"链接成功",Toast.LENGTH_SHORT).show();
        }
    };

    private Emitter.Listener onlineCount = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            Log.i("MM","获取数据");
            String id = "my_channel_01";
            String name="我是渠道名字";



            //普通通知
//            Notification.Builder builder = new Notification.Builder(LoginActivity.this);
//            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://blog.csdn.net/mcj19970614/article/details/80453285"));
//            PendingIntent pendingIntent = PendingIntent.getActivities(LoginActivity.this,0, new Intent[]{intent},0);
//            builder.setContentIntent(pendingIntent);
//            builder.setSmallIcon(R.mipmap.ic_launcher);
//            builder.setAutoCancel(true);
//            builder.setContentTitle("普通通知");
//            builder.setContentText("普通通知三层结构");
//            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//            //安卓版本8.0以上需要添加通道
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
//                notificationManager.createNotificationChannel(mChannel);
//                builder.setChannelId(id);
//            }
//            notificationManager.notify(2, builder.build());



            //折叠式通知
            Notification notification = new NotificationCompat.Builder(LoginActivity.this, id)
                .setAutoCancel(true)
                    .setSmallIcon(R.mipmap.quantwo)
                    .setContentTitle("折叠式")
                    .setContentText("sfasdfasdfasdf")
                    .setVisibility(VISIBILITY_PUBLIC)
                    .setNumber(3).build();

            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://blog.csdn.net/mcj19970614/article/details/80453285"));
            PendingIntent pendingIntent = PendingIntent.getActivities(LoginActivity.this,0, new Intent[]{intent},0);
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            //安卓版本8.0以上需要添加通道
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_NONE);
                mChannel.setShowBadge(true);
                notificationManager.createNotificationChannel(mChannel);
            }
            //未下拉的样式
//            RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.view_fold);
//            RemoteViews collapsed = new RemoteViews(getPackageName(),R.layout.wei_layout);
//              Notification notification = builder.build();
//              notification.contentView = collapsed;
//              notification.bigContentView = remoteViews;

            notificationManager.notify(2, notification);

















//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    Toast.makeText(LoginActivity.this,args[0].toString(),Toast.LENGTH_SHORT).show();
//                }
//            });
        }
    };
}



